package com.wondersgroup.insurance.dnuilearn.recyclerview.layoutmanager;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2017/6/30.
 */

public class SwipeCardManager extends LayoutManager {
    Context mContext;

    public SwipeCardManager(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
//        super.onLayoutChildren(recycler, state);
        //h缓存的核心机制之一
            detachAndScrapAttachedViews(recycler);

        int childCount  =  getItemCount();
        int initPosition;

        if (childCount < CardConfig.MAX_SHOW_COUNT){
            initPosition = 0;
        }else {
            initPosition = childCount - CardConfig.MAX_SHOW_COUNT;
        }
        for (int position =  initPosition ;position < childCount; position++){
            //从缓存获取view
            View child = recycler.getViewForPosition(position);
            addView(child);
            measureChild(child,0,0);
            int decorateWith = getDecoratedMeasuredWidth(child);
            int decorateHeight = getDecoratedMeasuredHeight(child);
            int widthSpace = getWidth() - decorateWith;
            int heightSpace = getHeight() - decorateHeight;
            int halfWidthSpace = widthSpace >>1;
            int halfHeightSpace = heightSpace >>1;
            layoutDecorated(child,halfWidthSpace,halfHeightSpace,halfWidthSpace+decorateWith,halfHeightSpace+decorateHeight);

            int level = childCount - position - 1;

            if (level > 0){
                child.setScaleX(1 - CardConfig.SCALE_GAP * level);
                child.setScaleY(1- CardConfig.SCALE_GAP * level);
                if (level < CardConfig.MAX_SHOW_COUNT -1){// 0  1  2
                    child.setTranslationY(CardConfig.TRANS_Y_GAP*level);
                }else {//3 - 1  = 2 最后一个 和倒数一个偏移量一致
                    Log.e("", "level = "+level);
                    child.setTranslationY(CardConfig.TRANS_Y_GAP* (level - 1));
                }

            }
        }
    }
}